// 

//Huang,Haiqiao coded on Dec.2009


#include "stdafx.h"
#include <iostream>

#include <stdlib.h>

#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <math.h>
#define GLUT_DISABLE_ATEXIT_HACK
#include <GL/glut.h>  

using namespace std;


float imgdata[500][500];
int w=0;
int h=0;
float scalar=50;//scalar of converting pixel color to float coordinates

void renderScene(void) {

	glClear (GL_COLOR_BUFFER_BIT);
	glLoadIdentity();// Reset the coordinate system before modifying 
	gluLookAt (0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
	//glRotatef(-30, 0.0, 1.0, 0.0); //rotate about the x axis
	glRotatef(-180, 0.0, 0.0, 1.0); //rotate about the z axis
	glRotatef(-180, 0.0, 1.0, 0.0); //rotate about the y axis

	float imageCenterX=w*.5;
	float imageCenterY=h*.5;
	float x,y,z;

	glPointSize(1.0); 
	glBegin(GL_POINTS);//GL_POINTS
	for (int i=0;i<h;i++){ 
		for (int j=0;j<w;j++){
			// color interpolation 
			glColor3f(1-imgdata[i][j]/255, imgdata[i][j]/255, imgdata[i][j]/255);
			x=((float)j-imageCenterX)/scalar;
			y=((float)i-imageCenterY)/scalar;
			z=imgdata[i][j]/scalar; 
			glVertex3f(x,y,z); 
		}
	}
	glEnd();
	glFlush();
}



void reshape (int w, int h) {
	glViewport (0, 0, (GLsizei)w, (GLsizei)h);
	glMatrixMode (GL_PROJECTION);
	glLoadIdentity ();
	gluPerspective (60, (GLfloat)w / (GLfloat)h, 1.0, 100.0);
	glMatrixMode (GL_MODELVIEW);
}


void displayDisparity(IplImage* disparity){

	double xyscale=100;
	int j=0;
	int i=0;
	CvScalar s;

	//accessing the image pixels
	for (i=0;i<h;i++){ 
		for (j=0;j<w;j++){
			s=cvGet2D(disparity,i,j);
			imgdata[i][j]=s.val[0];//for disparity is a grey image.
		}
	} 
}


int dispopenGL(int argc, char** argv,IplImage* imgGrey) 
{  
// 	cout << "OpenCV and OpenGL working together!"<<endl; 
// 	char* filename="D:\\OpenCV_stuff\\SampleImages\\tsuDisparity.bmp";
// 	IplImage* imgGrey = cvLoadImage(filename,0); //read image as a grey one 
// 	if (imgGrey==NULL){
// 		cout << "No valid image input."<<endl; 
// 		char c=getchar();
// 		return 1;
// 	} 
	w=imgGrey->width;
	h=imgGrey->height;

	displayDisparity(imgGrey); 
	cvNamedWindow("original", CV_WINDOW_AUTOSIZE );
	cvShowImage( "original", imgGrey );

	//------------------OpenGL-------------------------
	
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DEPTH | GLUT_SINGLE | GLUT_RGBA);
	glutInitWindowPosition(100,100);
	glutInitWindowSize(500,500);
	glutCreateWindow("3D disparity image");
	glutDisplayFunc(renderScene);

	glutReshapeFunc (reshape);
	glutMainLoop();


	cvWaitKey(0); 
	//release opencv stuff.
	cvReleaseImage(&imgGrey);
	cvDestroyWindow("Original");

	return 0; 
}
